import { ref } from 'vue'
import * as echarts from 'echarts'


export function useProductionTrendChart() {
  const productionTrendChart = ref(null)

  // 初始化图表的通用函数
  const initChart = (chartRef, option) => {
    if (!chartRef.value) return
    const chart = echarts.init(chartRef.value)
    chart.setOption(option)

    // 添加响应式调整
    window.addEventListener('resize', () => {
      chart.resize()
    })

    return chart
  }

  // 图表6：生产效能统计 - 饼图
  const initProductionTrendChart = async (data) => {
    // 直接使用API返回的数据
    let { months, productionValues } = data;
    // 转换数据格式为饼图所需格式
    const pieData = months.map((month, index) => ({
      name: month,
      value: productionValues[index]
    }));

    // 饼图颜色配置
    const pieColors = [
      '#ff7875', '#ffa940', '#ffec3d', '#73d13d', '#40a9ff',
      '#597ef7', '#9254de', '#f759ab', '#ff4d4f'
    ];

    const option = {
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        borderColor: '#1890ff',
        textStyle: { color: '#fff' },
        formatter: '{a} <br/>{b}: {c}万元 ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: { color: '#fff', fontSize: 11 }
      },
      series: [{
        name: '总产值',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#141414',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData,
        color: pieColors
      }]
    }

    initChart(productionTrendChart, option)
  };

  return {
    productionTrendChart,
    initProductionTrendChart
  }
}
